var contentPlace = '#content';
var templatesPath = 'templates/';
var apiUrl = 'api/';

var Main = {
    token: null,
    verifier: null,

    showAuth: function() {
	$.get(templatesPath + 'auth',
	    function (response, status) {
		$(contentPlace).html(response);
		$.getJSON(apiUrl + '?method=authUrl',
	    	    function (data) {
			if (data.status == 'OK') {
			    $('#authUrl').attr('href', data.result);
			}
	    	    }
		);
	    }
	)
    },
    
    setUserData: function() {
	$.getJSON(apiUrl + '?method=userInfo&token=' + this.token + '&verifier=' + this.verifier,
	    function (data) {
		if (data.status == 'AUTH') Main.showAuth();
		else {
		    $('#ui_name').html(data.result.data.name);
		}
	    }
	);
    },
    
    setUserAccount: function() {
	$.getJSON(apiUrl + '?method=userAccount&token=' + this.token + '&verifier=' + this.verifier,
	    function (data) {
		if (data.status == 'AUTH') Main.showAuth();
		else {
		    $('#ui_account').html(data.result.data.account);
		}
	    }
	);
    },
    
    setUserChannels: function () {
	$.getJSON(apiUrl + '?method=readerList&token=' + this.token + '&verifier=' + this.verifier,
	    function (data) {
		if (data.status == 'AUTH') Main.showAuth();
		else {
		    $('#channels').empty();
		    var img;
		    $(data.result.data.channels).each(function(index, el) {
			img = el.image?el.image.url:'http://real.greatiful.com/media/img/en/icon-about-footer.png';
			$('<li><div class="first"><img src="' + img + '" alt="' + el.title + '" /></div><div class="title">' + el.title + '</div></li>').click(function () {Main.showChannel($(this).data('channelID'))}).data('channelID', el.id).appendTo('#channels');
		    });
		}
	    }
	);

    },

    showPublisher: function(id) {
	Main.showChannels({pid: id});
    },

    showCategory: function(id) {
	Main.showChannels({category: id});
    },

    showLanguage: function(id) {
	Main.showChannels({language: id});
    },

    showChannels: function (params) {
	$.get(templatesPath + 'channels', function (response, status) {
 	    $(contentPlace).html(response);
    	    $.post(apiUrl + '?method=channelsList&token=' + Main.token + '&verifier=' + Main.verifier, params,
		function (data) {
		    if (data.status == 'AUTH') Main.showAuth();
		    else {
			if (params) {
				for (index in params) {
					var m = $('#searchForm input[name="' + index + '"]');
					if (m) m.val(params[index]);
				}
			}
			$('#searchForm').submit(function () {
				var inputs = $('#searchForm :input');
				var values = {};
				$(inputs).each(function () {values[this.name] = $(this).val();});
				Main.showChannels(values); return false}
			);
		        $('#pages').empty();
		        for (var i = 1; i <= data.result.data.pages; i++) {
		    	    if (i == data.result.data.page) {
		    		$('<b>' + i + ' </b> ').appendTo('#pages');
		    	    } else {
		    		var prm = {};
		    		if (params) prm = params;
		    		prm.page = i; 
		    		$('<a href="#page' + i + '">' + i + '</a>').click(function () {Main.showChannels($(this).data('params')); return false;}).appendTo('#pages').data('params', prm);
		    		$('#pages').append('&nbsp;');
		    	  }
		        }
		        $(data.result.data.channels).each(function (index, el) {
		    	    var id = 'channel' + el.id;
		    	    $('#channelTemplate').clone().appendTo('#channelsList').attr('class', 'channel').attr('id', id).css('display', 'inline');
			    if (el.image) {
				$('<img src="' + el.image.url + '" alt="' + el.title + '" />').appendTo('#' + id + ' .image'); 
			    }
		    	    $('#' + id + ' .title').html(el.title).data('channelID', el.id).click(function () {Main.showChannel($(this).data('channelID'))});
		    	    $('#' + id + ' .description').html(el.description);
		    	    $('#' + id + ' .publisher a').html(el.publisher.title).data('publisherID', el.publisher.id).click(function () {Main.showPublisher($(this).data('publisherID'));});
		    	    $('#' + id + ' .basic .category').html(el.category).data('category', el.category).click(function() {Main.showCategory($(this).data('category'))});
		    	    $('#' + id + ' .basic .language').html(el.language).data('language', el.language).click(function () {Main.showLanguage($(this).data('language'))});
		    	    	if (el.type) {
					var type = '';
					for (var i=0; i < el.type.length; i++) {
						type+= el.type[i] + ' ';
					}
					$('#' + id + ' .priceinfo .type').html(type);
				}
	    	    		$('#' + id + ' .priceinfo .price').html(el.price);
				var d = new Date(el.lastBuildDate);
				$('#' + id + ' .more .builddate').html(d.getDate() + '/' + d.getMonth() + ' ' + d.getHours() + ':' + d.getMinutes());
				dat = new Date(el.pubDate);
				$('#' + id + ' .more .pubdate').html(d.getDate() + '/' + d.getMonth() + ' ' + d.getHours() + ':' + d.getMinutes());
				$('#' + id + ' .basic .link').attr('href', el.link);
				if (el.subscriptionIsActive) {
					$('#' + id + ' .subscribe').hide();
					$('#' + id + ' .unsubscribe').data('channelID', el.id).click(function () {Main.unsubscribeChannel($(this).data('channelID')); return false;});
				} else {
					$('#' + id + ' .unsubscribe').hide();
					var post = {id: el.id}
					if (el.type == 'month'/*$.inArray('month', el.type)*/) {post.type = 'month'; /*post.price = el.month; */}
					else if (el.type == 'free') /*$.inArray('free', el.type))*/ {post.type = 'free'; post.price = 30;} 
					$('#' + id + ' .subscribe').data('channel', el).click(function () {Main.subscribeChannel($(this).data('channel')); return false;});
				}
		    	});
		    }
		},
	    'json');
	});
    },

 	unsubscribeChannel: function (id) {
		if (confirm('Unsubscribe?')) {
                $.post(apiUrl + '?method=readerUnsubscribe&token=' + Main.token + '&verifier=' + Main.verifier, {channelID: id},
                function (data) {
                        if (data.status == 'AUTH') Main.showAuth();
                        else {
                                if (data.result.status == 'OK') {
                                        $('#' + id + ' .unsubscribe').hide();
					Main.setUserChannels();
                                        alert('Unsubscribed');
                                } else {
                                        alert('Error ' + data.result.errorText);
                                }
                        }
                },
                'json');			
		}
	},

	subscribeChannel: function (info) {
		if (confirm('Subscribe?')) {
		var post = {type: 'free', channelID: info.id};
		var msg = '';
		for (i in info.price) msg += i + '=' + info.price[i] + "\n";
		alert(msg);
		if ($.inArray('month', info.type) > -1) {
			post.type = 'month';
			post.price = info.price.month;
		} else if ($.inArray('ppv', info.type) > -1) {
			post.type = 'ppv';
		} else {
			post.type = 'free';
			if (info.price.free && info.price.free!=0 && info.price.free.length()) {
				post.price = info.price.free[0];
			} else post.price = 10;
		}
	        $.post(apiUrl + '?method=readerSubscribe&token=' + Main.token + '&verifier=' + Main.verifier, post,
                function (data) {
        		if (data.status == 'AUTH') Main.showAuth();
	                else {
				if (data.result.status == 'OK') {
					Main.setUserAccount();
					$('#' + info.id + ' .subscribe').hide();
					Main.setUserChannels();
					alert('Subscribed');
				} else {
					alert('Error ' + data.result.errorText);
				}
			}
		},
		'json');
		}
	},

	showChannel: function (cid, params) {
		$.get(templatesPath + 'items', function (response, status) {
 	    		$(contentPlace).html(response);
			$.post(apiUrl + '?method=channelItems&token=' + Main.token + '&verifier=' + Main.verifier + '&cid=' + cid, params,
			function (data) {
			    	if (data.status == 'AUTH') Main.showAuth();
			    	else {
			if (params) {
				for (index in params) {
					var m = $('#itemsFilter input[name="' + index + '"]');
					if (m) m.val(params[index]);
					if (m.attr('type') == 'checkbox') m.attr('checked', 'checked');
				}
			}
			$('#itemsFilter').submit(function () {
				var values = $('#itemsFilter').serializeJSON();
				Main.showChannel(cid, values); return false}
			);
					var ch = data.result.data;
					$('#channelName').html(ch.title);
					$('#channelPublisher').html(ch.publisher.title).data('publisherID', ch.publisher.id).click(function () {Main.showPublisher($(this).data('publisherID'))});
					$('#channelLanguage').html(ch.language).data('language', ch.language).click(function () {Main.showLanguage($(this).data('language'))});
 					$('#channelCategory').html(ch.category).data('category', ch.category).click(function () {Main.showCategory($(this).data('category'))});
					$(ch.items).each(function(index, el) {
						id = 'item' + el.id;
						$('#itemTemplate').clone().appendTo('#itemsList').attr('id', id).css('display', 'inline');
						Main._updateItem(el, '#' + id);
						
					});
				}
			}, 'json');
		});
	},

	_updateItem: function (item, placeID) {
		$(placeID + ' .title').html(item.title);
		$(placeID + ' .description').html(item.description);
		if (item.image && item.image.url) {
			$(placeID + ' .image').html('<img src="' + item.image.url + '" alt="" />');
		}
		$(placeID + ' .type').html(item.type);
		$(placeID + ' .pubdate').html(item.pubDate);
		if (item.authors.length) {
			var s = '';
			for (var i = 0; i < item.authors.length; i++) s+= item.authors[i].name;
			$(placeID + ' .authors').html(s);
		}
		if (item.isPreview) {
			$(placeID + ' .preview').css('display', 'block');
			$(placeID + ' .preview a').click(function () {Main.updateItem(item.id); return false;});
		} else {
			$(placeID + ' .preview').css('display', 'none');
		}
		$(placeID + ' .marked').css('display', item.marked?'none':'inline');
		$(placeID + ' .link').attr('href', item.link);
		if (item.type == 'ppv') {
			$(placeID + ' .ppv').css('display', 'inline');
			$(placeID + ' .ppv a b').text(item.price);
		} else $(placeID + ' .ppv').css('display', 'none');
		if (item.type == 'free') {
			if (item.donated) {
				$(placeID + ' .donate').css('display', 'none');
				$(placeID + ' .donated').css('display', '').
				$(placeID + ' .donated b').text(item.donated);
			} else {
				$(placeID + ' .donate').css('display', '');
				$(placeID + ' .donated').css('display', 'none');
			}
		} else $(placeID + ' .donate').css('display', 'none');
	},

    init: function() {
	this.token = $.getUrlVar('oauth_token');
	this.verifier = $.getUrlVar('oauth_verifier');
	if (this.token) {
	    this.setUserData();
	    this.setUserAccount();
	    this.setUserChannels();
	    this.showChannels();
	} else {
	    this.showAuth();
	}
    }
}

$.extend({
    getUrlVars: function() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for (var i = 0; i < hashes.length; i++) {
	    hash = hashes[i].split('=');
	    vars.push(hash[0]);
	    vars[hash[0]] = hash[1];
	}
	return vars;
    },
    
    getUrlVar: function(name) {
	return $.getUrlVars()[name];
    }
});

(function( $ ){
$.fn.serializeJSON=function() {
var json = {};
jQuery.map($(this).serializeArray(), function(n, i){
json[n['name']] = n['value'];
});
return json;
};
})( jQuery );

$().ready(function() {Main.init()});
